package com.example.demo.config;

import com.alibaba.fastjson.JSON;
import com.example.demo.entity.MessageNum;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    private final List<WebSocketSession> sessions = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("新客户端连接: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理客户端发送的消息
        System.out.println("收到消息: " + message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("客户端断开连接: " + session.getId());
    }

    public void sendMessageToAllClients(MessageNum message) {
        for (WebSocketSession session : sessions) {
            try {
                String msg = JSON.toJSONString(message);
                session.sendMessage(new TextMessage(msg));
                System.out.println("发送成功: " + session.getId()+" "+msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}